package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务表 服务实现类
 * </p>
 *
 * @author liuyp
 * @since 2024-12-11
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Resource
    private RegionMapper regionMapper;
    @Resource
    private ServeItemMapper serveItemMapper;

    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO dto) {
        /*//开启分页
        PageHelper.startPage(dto.getPageNo().intValue(), dto.getPageSize().intValue());
        //调用mapper查询列表
        List<ServeResDTO> list = baseMapper.selectServeListByRegionId(dto.getRegionId());
        Page<ServeResDTO> page = (Page<ServeResDTO>) list;
        //封装结果
        return new PageResult<ServeResDTO>((long) page.getPages(), page.getTotal(), list);*/

        //以后再开发遇到自定义SQL的分页：
        //  1. 在mapper里添加方法，配置自定义的SQL语句。 SQL语句里不需要limit、不需要order by，直接根据条件查列表即可
        //  2. 使用PageHelperUtils.selectPage(查询条件对象,  ()-> baseMapper.xxxx(参数值))
        return PageHelperUtils.selectPage(dto, () -> baseMapper.selectServeListByRegionId(dto.getRegionId()));
    }

    @Override
    public void add(List<ServeUpsertReqDTO> list) {
        for (ServeUpsertReqDTO dto : list) {
            //查询一下服务项，如果找不到服务项，就抛出异常
            ServeItem serveItem = serveItemMapper.selectById(dto.getServeItemId());
            if (serveItem == null) {
                //实际项目中，通常会有自定义的各种异常信息，由异常处理器进行统一处理
                throw new ForbiddenOperationException("服务项不存在");
            }
            //如果服务项没有被启用，也不允许添加区域服务。
            // 代码里尽量避免魔法值(没头没尾突然出现的数值)
            // 解决方式：1. 定义到常量里，取常量值； 2. 定义到枚举里，取枚举项的值
            if (serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
                throw new ForbiddenOperationException(serveItem.getName() + "服务不可用");
            }

            //如果当前区域里已经有这个服务了，不允许重复添加
            Integer count = lambdaQuery()
                    .eq(Serve::getRegionId, dto.getRegionId())
                    .eq(Serve::getServeItemId, dto.getServeItemId())
                    .count();
            if (count > 0) {
                throw new ForbiddenOperationException(serveItem.getName() + "服务项已存在");
            }
            //获取当前区域的cityCode
            Region region = regionMapper.selectById(dto.getRegionId());
            if (region == null) {
                throw new ForbiddenOperationException("此区域不存在");
            }

            //把数据封装成Serve对象，插入到serv表里
            Serve serve = BeanUtil.toBean(dto, Serve.class);
            serve.setCityCode(region.getCityCode());
            save(serve);
        }
    }

    @Override
    public void updatePrice(Long serveId, BigDecimal price) {
        boolean updated = lambdaUpdate()
                .set(Serve::getPrice, price)
                .eq(Serve::getId, serveId)
                .update();
        if (!updated) {
            throw new CommonException("修改价格失败");
        }
    }

    @Override
    public void onSale(Long serveId) {
        //1. 区域服务如果是已上架状态：不允许重复上架
        Serve serve = getById(serveId);
        if (serve == null) {
            throw new ForbiddenOperationException("区域服务不存在");
        }
        if (serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务已上架");
        }

        //2. 如果服务项没有启用：不允许上架
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (serveId == null) {
            throw new ForbiddenOperationException("服务项不存在");
        }
        if (serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务项未启用，不能上架");
        }

        //3. 修改为上架状态
        boolean updated = lambdaUpdate()
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .eq(Serve::getId, serveId)
                .update();
        if (!updated) {
            throw new CommonException("服务上架失败");
        }
    }
}
